<template>
  <el-dialog
    :title="formData.id ? '编辑中文' : '新增中文'"
    :visible="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    center
  >
    <el-form
      ref="addEditForm"
      v-loading="isLoading > 0"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="add-edit-form"
    >
      <el-form-item label="中文" prop="zh">
        <el-input v-model="formData.zh" />
      </el-form-item>
      <el-form-item label="声音类型" prop="voice_type">
        <el-input v-model="formData.voice_type" />
      </el-form-item>

      <el-form-item class="submit-box">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button v-if="!formData.id" @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const emptyFormData = {
  zh: null,
  voice_type: 1
}
let formData = null
import _ from 'lodash'
import { removeNoChangeValue } from '@/utils/tools'
import { addOneZhSpeech, updateOneZhSpeech } from '@/api/zh_speech'
export default {
  name: 'ZhSpeechAddEdit',
  components: {
  },
  props: {},
  data() {
    return {
      dialogVisible: false,
      isLoading: 0,
      formData: {},
      rules: {
        zh: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {},
  methods: {
    handleClose() {
      this.dialogVisible = false
    },
    open(row) {
      this.dialogVisible = true
      if (row) {
        formData = _.cloneDeep(row)
      } else {
        formData = _.cloneDeep(emptyFormData)
      }
      this.resetForm()
    },
    resetForm() {
      this.formData = _.cloneDeep(formData)
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    submitForm() {
      if (this.isLoading > 0) return
      this.$refs.addEditForm.validate(async vaild => {
        if (!vaild) return
        try {
          this.isLoading++
          if (this.formData.id) {
            const _formData = removeNoChangeValue(this.formData, formData)
            if (Object.keys(_formData).length === 1) {
              this.$message.error('您没有修改任何值！')
              return
            }
            await updateOneZhSpeech(_formData)
          } else {
            await addOneZhSpeech(this.formData)
          }
          this.$emit('refresh')
          this.handleClose()
        } finally {
          this.isLoading--
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.submit-box {
  display: flex;
  justify-content: flex-end;
}
</style>
